package com.example.springboot003mysql;

import jakarta.annotation.Nonnull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextHolder implements ApplicationContextAware, ApplicationEventPublisherAware {
    private static ApplicationContext context;

    private static ApplicationEventPublisher publisher;

    public void setApplicationContext(@Nonnull ApplicationContext context) throws BeansException {
        ApplicationContextHolder.context = context;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static String getRequiredProperty(String key) {
        return context.getEnvironment().getRequiredProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        return context.getEnvironment().getProperty(key, defaultValue);
    }

    public static <T> T getProperty(String key, Class<T> cls) {
        return context.getEnvironment().getProperty(key, cls);
    }

    public static String getProperty(@Nonnull String key) {
        String realKey;
        String defaultValue = null;

        int index = key.indexOf(":");
        if (index != -1) {
            realKey = key.substring(0, index);
            defaultValue = key.substring(index + 1);
        } else {
            realKey = key;
        }

        String property = context.getEnvironment().getProperty(realKey);
        if (property == null) {
            if (defaultValue == null) {
                throw new RuntimeException(String.format("Key %s does not exist and default-value does not exist", realKey));
            }
            return defaultValue;
        }

        return property;
    }

    public static String val(String key) {
        return getProperty(key);
    }

    @Override
    public void setApplicationEventPublisher(@Nonnull ApplicationEventPublisher applicationEventPublisher) {
        publisher = applicationEventPublisher;
    }

    /**
     * 发布一个事件
     */
    public static void publish(Object obj) {
        publisher.publishEvent(obj);
    }

    public static <T> T getBean(Class<T> t) {
        return context.getBean(t);
    }
}

